package com.webserver.http;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpServletResponse {
    private Socket socket;

    private int statusCode=200;//默认为200
    private String statusReason="OK";

    private Map<String,String> headers=new HashMap<>();
    private File contentFile;
    private ByteArrayOutputStream baos;
    private byte[] contentData;//作为响应正文数据的字节数组

    public HttpServletResponse(Socket socket){
        this.socket=socket;
    }


    public void response() throws IOException {
        sendBefore();
        sendStatusLine();
        sendHeaders();
        sendContent();
    }

    private void sendBefore(){
        //先判断baos是否为null，如果不是null则说明存在动态数据
        if (baos!=null){
            contentData=baos.toByteArray();
        }
        //如果动态数据数组不为null，添加响应头Content-Length
        if (contentData!=null){
            addHeader("Content-Length",contentData.length+"");
        }
    }
    private void sendStatusLine() throws IOException {
        println("HTTP/1.1 "+statusCode+" "+statusReason);
    }

    private void sendHeaders() throws IOException {
        Set<Map.Entry<String,String>> entrySet=headers.entrySet();
        for (Map.Entry<String,String> entry:entrySet){
            String key=entry.getKey();
            String value=entry.getValue();
            println(key+": "+value);
        }
        println("");
    }
    private void sendContent() throws IOException {
        if (contentData!=null){//拥有动态数据
            OutputStream out=socket.getOutputStream();
            out.write(contentData);
        }else if (contentFile!=null){
            OutputStream out=socket.getOutputStream();
            try(FileInputStream fis = new FileInputStream(contentFile);) {

                byte[] bytes = new byte[1024 * 10];
                int len;
                while ((len = fis.read(bytes)) != -1) {
                    out.write(bytes, 0, len);
                }
            }
        }
    }
    private void println(String line) throws IOException {
        OutputStream out=socket.getOutputStream();
        byte[] bytes=line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(bytes);
        out.write(13);
        out.write(10);
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
        String contentType=null;
        try {
            contentType= Files.probeContentType(contentFile.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (contentType!=null){
            addHeader("Content-Type",contentType);
        }
        addHeader("Content-Length",contentFile.length()+"");
    }
    public void addHeader(String name,String value){
        headers.put(name,value);
    }
    public OutputStream getOutputStream(){
        if (baos==null){
            baos=new ByteArrayOutputStream();
        }
        return baos;
    }

    public PrintWriter getWriter(){
        return new PrintWriter(
                new BufferedWriter(
                        new OutputStreamWriter(
                                getOutputStream(),StandardCharsets.UTF_8
                        )
                ),true
        );
    }

    /**
     * 设置响应头Content-Type的值
     * @param mime
     */
    public void setContentType(String mime){
        addHeader("Content-Type",mime);
    }

    public void sendRedirect(String location){
        /*
        重定向的规则:
        响应中的状态代码为302
        响应头中应当包含Location
        没有响应正文
         */
        this.statusCode=302;
        this.statusReason="Moved Temporarily";
        addHeader("Location",location);
    }
}
